'use client'

import { Select } from "@radix-ui/themes";
import axios from "axios";

import React, { useEffect, useState } from 'react';
import { User } from "@prisma/client";
import { Issue } from "@prisma/client";
import toast, { Toaster } from "react-hot-toast"

const AssigneeSelect = ({ issue }: { issue: Issue }) => {
    const [users, setUsers] = useState<User[]>([]);
    useEffect(() => {
        const fetchUsers = async () => {
            const { data } = await axios.get<User[]>("/api/users");
            setUsers(data);
        }
        fetchUsers().then(() => { });
    }, [])

    const assignIssue = (userId:string)=>{
        axios.patch("/api/issues/" + issue.id, {
            assignedToUserId: userId === "unassigned" ? null : userId,
        })
            .catch(() => {
                toast.error("Changes could not be saved.");
            })
    }

    return (
        <>
            <Select.Root
                onValueChange={assignIssue}
                defaultValue={issue.assignedToUserId || 'unassigned'}
            >
                <Select.Trigger placeholder={"Assign"}></Select.Trigger>
                <Select.Content >
                    <Select.Group>
                        <Select.Label>Suggestions</Select.Label>
                        <Select.Item value="unassigned">Unassigned</Select.Item>
                        {users.map((user) => (
                            <Select.Item value={user.id} key={user.id}>{user.name}</Select.Item>
                        ))}
                    </Select.Group>
                </Select.Content>
            </Select.Root>
            <Toaster />
        </>
    );
};

export default AssigneeSelect;